﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Management;


namespace WEI_Share.Helpers
{
    public sealed class WMISystemInfo
    {
        #region Constructor
        /// <summary>
        /// Private constructor
        /// </summary>
		private WMISystemInfo()
        {
        }
        #endregion


		/// <summary>
		/// used to determine if the process is still running
		/// http://www.techimo.com/forum/applications-operating-systems/117464-need-vbulletin-script-check-see-if-process-running.html
		/// </summary>
		/// <param name="processName"></param>
		/// <returns></returns>
		public static bool? IsProcessStillRunning(string processName)
		{
			bool? response = null;

			try
			{
				ManagementObjectSearcher searcher =
					new ManagementObjectSearcher("root\\CIMV2",
					"SELECT * FROM Win32_Process");

				foreach (ManagementObject queryObj in searcher.Get())
				{
					if(string.Compare(queryObj["Name"].ToString(), processName, StringComparison.OrdinalIgnoreCase) == 0)
					{
						response = true;
						break;
					}
				}

				if(!response.HasValue)
					response = false;
			}
			catch (Exception ex)
			{
				System.Windows.MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
			}

			return response;
		}


        /// <summary>
        /// used to retrieve the basic system/board info
        /// </summary>
        /// <returns></returns>
        public static List<WMIItem> GetComputerSystemItems()
        {
            List<WMIItem> response = new List<WMIItem>();

            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher("root\\CIMV2",
                "SELECT * FROM Win32_ComputerSystem");

            foreach (ManagementObject queryObj in searcher.Get())
            {
                response.Add
                    (
                        new WMIItem()
                        {
                            Key = "Manufacturer",
                            Value = queryObj["Manufacturer"]
                        }
                    );
                response.Add
                    (
                        new WMIItem()
                        {
                            Key = "Model",
                            Value = queryObj["Model"]
                        }
                    );
                response.Add
                    (
                        new WMIItem()
                        {
                            Key = "SystemType",
                            Value = queryObj["SystemType"]
                        }
                    );
                break;
            }

            return response;
        }

        /// <summary>
        /// used to retrieve the memory info
        /// </summary>
        /// <returns></returns>
        public static List<WMIItem> GetPhysicalMemory()
        {
            List<WMIItem> response = new List<WMIItem>();

            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher("root\\CIMV2",
                "SELECT * FROM Win32_PhysicalMemory");

            foreach (ManagementObject queryObj in searcher.Get())
            {
                response.Add
                    (
                        new WMIItem()
                        {
                            Key = "MemoryType",
                            Value = queryObj["MemoryType"]
                        }
                    );
                response.Add
                    (
                        new WMIItem()
                        {
                            Key = "Speed",
                            Value = queryObj["Speed"]
                        }
                    );

                break;
            }

            return response;
        }



        /// <summary>
        /// used to retrieve the memory info
        /// </summary>
        /// <returns></returns>
        public static List<WMIItem> GetNetworkCardInfo()
        {
            List<WMIItem> response = new List<WMIItem>();
                        
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher("root\\CIMV2",
                "SELECT * FROM Win32_NetworkAdapterConfiguration");

            foreach (ManagementObject queryObj in searcher.Get())
            {
                if ((bool)queryObj["IPEnabled"] == true)
                {

                    response.Add
                        (
                            new WMIItem()
                            {
                                Key = "MacAddress",
                                Value = queryObj["MacAddress"]
                            }
                        );

                    break;
                }
            }

            return response;
        }


		public static List<DriveData> GetPrimaryDriveInfo(string deviceID)
		{
			List<DriveData> response = new List<DriveData>();
			
			//get drives/letters
			ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT Caption, DeviceID FROM Win32_DiskDrive");
			foreach (ManagementObject queryObj in searcher.Get())
			{
				if (string.Compare(queryObj["DeviceID"].ToString(), deviceID, true) == 0)
				{
					ManagementObjectSearcher searcherSub =
						new ManagementObjectSearcher("root\\CIMV2", "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + queryObj["DeviceID"] + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition");
					foreach (ManagementObject queryObjSub in searcherSub.Get())
					{
						ManagementObjectSearcher searcherSubSub =
							new ManagementObjectSearcher("root\\CIMV2", "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + queryObjSub["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition");
						foreach (ManagementObject queryObjSubSub in searcherSubSub.Get())
						{
							DriveData current = new DriveData();
							current.DiskDeviceID = queryObj["DeviceID"].ToString();
							current.LogicalDeviceID = queryObjSubSub["DeviceID"].ToString();

							//get size info
							ManagementObjectSearcher searcherLogical = new ManagementObjectSearcher("root\\CIMV2", "SELECT Freespace, Size FROM Win32_LogicalDisk WHERE DeviceID='" + queryObjSubSub["DeviceID"].ToString() + "'");
							foreach (ManagementObject queryObjCurrent in searcherLogical.Get())
							{
								string currentValue = queryObjCurrent["Size"].ToString();
								if (!string.IsNullOrEmpty(currentValue))
									current.Size = Convert.ToInt64(currentValue);

								currentValue = queryObjCurrent["FreeSpace"].ToString();
								if (!string.IsNullOrEmpty(currentValue))
									current.Freespace = Convert.ToInt64(currentValue);
							}

							response.Add(current);
						}
					}
				}
			}

			return response;
		}

    }
}
